<template>
  <div
    shadow="never"
    class="link-form-render"
    v-show="display"
  >
  <el-text v-show="!display" type="info" class="mx-1">此处显示外链表单视图</el-text>
    <iframe
      v-show="display"
      src=""
      frameborder="0"
      @load="onLoad"
      v-bind:style="sizeRef"
      ref="iframeRef"
    ></iframe>
  </div>
</template>

<script setup>
import {
  reactive,
  ref,
  unref,
  nextTick,
  watch,
  computed,
  onMounted,
  onBeforeUnmount,
} from "vue";
const props = defineProps({
  src: {
    type: String,
    default: "",
  },
});
const display = ref(true);
const iframeRef = ref(null);
const sizeRef = ref({
  height: "300px",
  width: "100%",
});

onMounted(() => {
  window.addEventListener("message", onIframeSizeChange);
});
onBeforeUnmount(() => {
  window.addEventListener("message", onIframeSizeChange);
});
const onIframeSizeChange = (e) => {
  /*
  子页面通过post message 通知父页面更新组件展示
  */
  if (e && e.data) {
    const data = e.data;

    if (data.event === "setFormIframeHeight") {
      sizeRef.value.height = data.height + "px";
    } else if (data.event === "setFormIframeWidth") {
      sizeRef.value.width = data.width + "px";
    }
  }
};
const onLoad = () => {
  //改变iframe 容器的高度
  if (iframeRef.value) {
    setTimeout(() => {
      try {
        const cIframe = iframeRef.value;
        let aWindow = cIframe.contentWindow;
        let aWindowHeight =
          aWindow.document.documentElement.scrollHeight ||
          aWindow.document.body.scrollHeight;
        let doc = cIframe.contentDocument || cIframe.document;
        let cHeight = Math.max(
          doc.body.clientHeight,
          doc.documentElement.clientHeight
        );
        let sHeight = Math.max(
          doc.body.scrollHeight,
          doc.documentElement.scrollHeight
        );
        let lheight = Math.max(cHeight, sHeight);
        let finalHeight = Math.max(lheight, aWindowHeight);
        if (finalHeight > 0) {
          cIframe.style.height = finalHeight + "px";
          sizeRef.value.height = finalHeight + "px";
        }
      } catch (e) {
        throw new Error("自定义错误setIframeHeight Error");
      }
    }, 1500);
  }
};
const loadFrame = () => {
  if (iframeRef.value && props.src && props.src.indexOf("http") > -1) {
    iframeRef.value.contentWindow.location.href = props.src;
    display.value = true;
  } else {
    display.value = false;
  }
};
watch(
  () => props.src,
  () => {
    loadFrame();
  }
);

onMounted(() => {
  loadFrame();
});
</script>

<style scoped>
.link-form-render {
 border-radius: 4px;
 border: 1px solid #dce3e8;
 margin: 5px 0px 5px 0px;  
 padding: 3px;
 min-height: 30px;
}
</style>
